package com.webank.ai.fate.serving.adaptor.dataaccess;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AESUtil {

    // 密匙
//    private static final String KEY = "cehfgZxofzOKIcid";
    private static final String KEY = "AbDYyQhWnzQYrXfE"; // 测试
    // 偏移量
    private static final String OFFSET = "0123456789abcdef";
    // 编码
    private static final String ENCODING = "UTF-8";
    //算法
    private static final String ALGORITHM = "AES";
    // 默认的加密算法
    private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";


    /**
     * 加密
     * @param data
     * @return
     * @throws Exception
     * @return String
     * @author tyg
     * @date   2018年6月28日下午2:50:35
     */
    public static String encrypt(String data) throws Exception {
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("ASCII"), ALGORITHM);
        IvParameterSpec iv = new IvParameterSpec(OFFSET.getBytes());//使用CBC模式，需要一个向量iv，可增加加密算法的强度
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(data.getBytes(ENCODING));
        return new BASE64Encoder().encode(encrypted);//此处使用BASE64做转码。
    }

    /**
     * 解密
     * @param data
     * @return
     * @throws Exception
     * @return String
     * @author tyg
     * @date   2018年6月28日下午2:50:43
     */
    public static String decrypt(String data) throws Exception {
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("ASCII"), ALGORITHM);
        IvParameterSpec iv = new IvParameterSpec(OFFSET.getBytes());//使用CBC模式，需要一个向量iv，可增加加密算法的强度
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
        byte[] buffer = new BASE64Decoder().decodeBuffer(data);
        byte[] encrypted = cipher.doFinal(buffer);
        return new String(encrypted, ENCODING);//此处使用BASE64做转码。
    }

    public static void main(String[] args) throws Exception {
//        String token = "3mQooRkbM0J2ccUzh21CBea+Bbbb5aup9BCuRXH7RYok2ilVGFxN1VmE8gDdV7QgrZTHi+XQSu+DM1Mq+ARZWw==";
        String token = "3P1ts+dY3Xy1n1rM6eBm3HuEaroiVHAvwwZpwaLaexiQ1vIoJQNFkdFl7aab8i2bT9QA0i5shS9GLWzfI+JjQA==";
        String de = "{\"res\":\"9f1446df0b953737944081c362df9c718e296d5d\",\"status\":200}";

        String decrypt = decrypt(token);
        System.out.println(decrypt);
    }

}
